package cn.xinfei.xdecision.manager.controller.data.datainterface;


import cn.xinfei.xdecision.common.model.common.ResponseEntityBuilder;
import cn.xinfei.xdecision.common.model.common.ResponseEntityDto;
import cn.xinfei.xdecision.common.model.common.requestParam.QueryListParam;
import cn.xinfei.xdecision.common.model.datax.datainterface.request.InterfaceUpdateStatusParam;
import cn.xinfei.xdecision.common.model.datax.datainterface.request.VarInterfaceInfoDTO;
import cn.xinfei.xdecision.common.model.datax.datainterface.request.VarInterfaceInfoReqVO;
import cn.xinfei.xdecision.common.model.datax.datainterface.v2.VarInterfaceInfo;
import cn.xinfei.xdecision.common.model.datax.enums.ExecutorType;
import cn.xinfei.xdecision.common.model.login.SSOUser;
import cn.xinfei.xdecision.common.model.login.SessionManager;
import cn.xinfei.xdecision.common.service.datax.datainterface.v2.VarInterfaceInfoService;
import cn.xinfei.xdecision.common.utils.constant.OperateNameConst;
import cn.xinfei.xdecision.common.utils.constant.OperateTypeEnum;
import cn.xinfei.xdecision.common.utils.exception.ApiException;
import cn.xinfei.xdecision.common.utils.exception.enums.ErrorCodeEnum;
import cn.xinfei.xdecision.common.utils.util.BeanUtilsPlus;
import cn.xinfei.xdecision.data.core.frame.executors.http.HttpExecutorClient;
import cn.xinfei.xdecision.data.core.vo.VarInterfaceInfoVO;
import cn.xinfei.xdecision.manager.web.aop.ArchivesLog;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 提供interface相关接口
 *
 * @apiDefine interface 接口管理
 */
@Api(tags = "变量中心-接口源管理")
@RestController
@RequestMapping("datamanage/interface")
public class InterfaceController {

    @Autowired
    VarInterfaceInfoService interfaceService;

    @Autowired
    HttpExecutorClient httpExecutorClient;

    @RequestMapping("testInterface")
    public String test() {
        String str = "{\n" +
                "    \"status\": \"1\",\n" +
                "    \"error\": \"00000000\",\n" +
                "    \"msg\": null,\n" +
                "    \"data\": {\n" +
                "        \"name\": \"张三\",\n" +
                "        \"age\": 25\n" +
                "    }\n" +
                "}";
        return str;
    }

    /**
     * @api {POST} /v3/interface/getInterfaceInfo/{userId} 3.19. V3获取Interface信息
     * @apiGroup knowledge
     * @apiVersion 2.0.0
     * @apiParam {Long} userId :  用户id
     * @apiSuccess {String} status 状态：1成功，0失败
     * @apiParamExample {json} 请求示例：
     * {}
     * @apiSuccessExample {json} 成功返回数据示例：
     * {"status":"1","error":"00000000","msg":null,"data":{"userId":666,"name":"2021_4_6测试接口","versionCode":"test2021_4_6第二次输入","description":"接口测试","priority":0,"parentId":0,"author":135,"userId":135,"organId":46,"engineId":null,"status":1,"type":1,"isNon":null,"content":"test","created":"2021-04-06T08:38:17.000+00:00","updated":"2021-04-07T05:12:52.000+00:00","ruleType":0,"ruleAudit":2,"score":0,"lastLogical":"","ruleConditionVo":{"userId":14,"logical":"&&","fieldId":null,"operator":null,"fieldValue":null,"ruleId":666,"parentId":0,"conditionType":1,"createTime":"2021-04-06T08:38:26.000+00:00","updateTime":null,"insertTempId":null,"children":[{"userId":15,"logical":null,"fieldId":null,"operator":">","fieldValue":"1000","ruleId":666,"parentId":14,"conditionType":1,"createTime":"2021-04-06T08:38:26.000+00:00","updateTime":null,"insertTempId":null,"children":[],"tempParentId":null},{"userId":16,"logical":null,"fieldId":null,"operator":"<","fieldValue":"10000","ruleId":666,"parentId":14,"conditionType":1,"createTime":"2021-04-06T08:38:26.000+00:00","updateTime":null,"insertTempId":null,"children":[],"tempParentId":null}],"tempParentId":null},"ruleContentInfoList":[{"userId":16,"fieldId":10000,"fieldValue":"test01","ruleId":666},{"userId":17,"fieldId":10000,"fieldValue":"test02","ruleId":666}]}}
     */
    @ApiOperation(value = "获取Interface信息")
    @RequestMapping(value = "getInterfaceInfo/{id}", method = RequestMethod.POST)
    public ResponseEntityDto<VarInterfaceInfo> getInterfaceById(@PathVariable Long id) {
        if (id == null) {
            throw new ApiException(
                    ErrorCodeEnum.PARAMS_EXCEPTION.getCode(),
                    ErrorCodeEnum.PARAMS_EXCEPTION.getMessage()
            );
        }
        VarInterfaceInfo interfaceVo = interfaceService.selectInterfaceById(id);
        return ResponseEntityBuilder.buildNormalResponse(interfaceVo);
    }

    //测试http请求，并获得响应
    @ApiOperation(value = "测试http请求")
    @PostMapping("getHttpResponse")
    public ResponseEntityDto<JSONObject> getHttpResponse(@RequestBody VarInterfaceInfoReqVO interfaceInfo) {
        VarInterfaceInfoVO varInterfaceInfoVO = new VarInterfaceInfoVO();
        BeanUtils.copyProperties(interfaceInfo, varInterfaceInfoVO);
        JSONObject jsonResponse = httpExecutorClient.standardHttpResponse(varInterfaceInfoVO, ExecutorType.fromIsSyncCode(interfaceInfo.getIsSync()));
        return ResponseEntityBuilder.buildNormalResponse(jsonResponse);
    }

    @ApiOperation(value = "查询所有接口")
    @PostMapping("getInterfaceList")
    public ResponseEntityDto getInterfaceList(@RequestBody QueryListParam<VarInterfaceInfo> param) {

        SSOUser loginAccount = SessionManager.getLoginAccount();
        long organId = loginAccount.getOrganId();
        int pageNo = param.getPageNum() == null ? 1 : Integer.parseInt(param.getPageNum().toString());
        int pageSize = param.getPageSize() == null ? 10 : Integer.parseInt(param.getPageSize().toString());
        PageHelper.startPage(pageNo, pageSize);
        List<VarInterfaceInfo> interfaceList = interfaceService.getInterfaceList(organId);
        PageInfo<VarInterfaceInfo> pageInfo = new PageInfo<>(interfaceList);
        List<VarInterfaceInfoDTO> varInterfaceInfoDtos = BeanUtilsPlus.copyElements(interfaceList, VarInterfaceInfoDTO::new);
        HashMap<String, Object> responseMap = new HashMap<>();
        if (CollectionUtils.isEmpty(interfaceList)) {
            responseMap.put("pageInfo", new PageInfo<>());
            responseMap.put("klist", new ArrayList<>());
            return ResponseEntityBuilder.buildNormalResponse(responseMap);
        }
        responseMap.put("pageInfo", pageInfo);
        responseMap.put("klist", varInterfaceInfoDtos);
        return ResponseEntityBuilder.buildNormalResponse(responseMap);
    }

    //添加接口
    @ApiOperation(value = "添加接口")
    @PostMapping("addInterface")
    @ArchivesLog(type = OperateTypeEnum.CREATE, name = OperateNameConst.VariableOpt.ADD_INTERFACE)
    public ResponseEntityDto<VarInterfaceInfo> addInterface(@RequestBody VarInterfaceInfo interfaceVo) {
        VarInterfaceInfo insert = interfaceService.insert(interfaceVo);
        ResponseEntityDto<VarInterfaceInfo> ruleResponseEntityDto = ResponseEntityBuilder.buildNormalResponse(insert);
        return ruleResponseEntityDto;
    }

    //删除接口
    @ApiOperation(value = "删除接口")
    @PostMapping("deleteInterface")
    @ArchivesLog(type = OperateTypeEnum.DELETE, name = OperateNameConst.VariableOpt.DELETE_INTERFACE)
    public ResponseEntityDto<Boolean> deleteInterface(@RequestBody VarInterfaceInfo interfaceVo) {
        Boolean bool = interfaceService.deleteByPrimaryKey(interfaceVo);
        ResponseEntityDto<Boolean> ruleResponseEntityDto = ResponseEntityBuilder.buildNormalResponse(bool);
        return ruleResponseEntityDto;
    }

    //编辑接口
    @ApiOperation(value = "编辑接口")
    @PostMapping("updateInterface")
    @ArchivesLog(type = OperateTypeEnum.UPDATE, name = OperateNameConst.VariableOpt.UPDATE_INTERFACE)
    public ResponseEntityDto<VarInterfaceInfo> updateInterface(@RequestBody VarInterfaceInfo interfaceVo) {
        VarInterfaceInfo insert = interfaceService.update(interfaceVo);
        return ResponseEntityBuilder.buildNormalResponse(insert);
    }

    //更新接口状态
    @ApiOperation(value = "更新接口状态")
    @PostMapping("updateInterfaceStatus")
    @ArchivesLog(type = OperateTypeEnum.UPDATE, name = OperateNameConst.VariableOpt.UPDATE_INTERFACE_STATUS)
    public ResponseEntityDto updateStatus(@RequestBody InterfaceUpdateStatusParam param) {
        Long id = param.getId();
        Integer status = param.getStatus();
        if (id == null || status == null) {
            throw new ApiException(
                    ErrorCodeEnum.PARAMS_EXCEPTION.getCode(),
                    ErrorCodeEnum.PARAMS_EXCEPTION.getMessage()
            );
        }
        boolean updateResult = interfaceService.updateStatus(id, status);
        if (updateResult) {
            return ResponseEntityBuilder.buildNormalResponse(updateResult);
        } else {
            return ResponseEntityBuilder.buildErrorResponse(ErrorCodeEnum.VAR_INTERFACE_STATUS__ERROR);
        }

    }

}
